angular.module('imsApp').controller('campaignsUpdateController', ['$scope','$rootScope', '$state','CampaignsManager',"$uibModal", "ImsErr",
    function ($scope,$rootScope,$state,CampaignsManager,$uibModal,ImsErr) {

    var campaignsId = $state.params.campaignsId;

    $scope.codeTable = JSON.parse(localStorage.getItem('codeTable'));
    $scope.initData = {
        "adStyle": ["84", "82", "83", "81"],
        "tradeType":["101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "123", "124", "125", "126", "127"],
        "intervalHour":[{key:0},{key:1},{key:2},{key:3},{key:4},{key:5},{key:6},{key:7},{key:8},{key:9},{key:10},{key:11},{key:12},{key:13},{key:14},{key:15},{key:16},{key:17},{key:18},{key:19},{key:20},{key:21},{key:22},{key:23}]
    };

    //每日时段
    $scope.selectAll=function () {
        $scope.initData.intervalHour.forEach(function (item) {
            item.checked=true;
        })

    };
    $scope.unSelectAll=function(){
        $scope.initData.intervalHour.forEach(function (item) {
            if(item.checked){
                item.checked=false;
            }else {
                item.checked=true;
            }
        })
    };
    CampaignsManager.campaignsDetail(campaignsId).then(function (result) {
        $scope.adStyleIsDisable=angular.copy(result.data.adCampaignVO.adStyle);
        $scope.costStrategyIsDisable=angular.copy(result.data.adCampaignVO.costStrategy);
        $scope.costTypeIsDisable=angular.copy(result.data.adCampaignVO.costType);
        $scope.cpmNumIsDisable=angular.copy(result.data.adCampaignVO.cpmNum);
        $scope.cpcNumIsDisable=angular.copy(result.data.adCampaignVO.cpcNum);

        $scope.adCampaignVO = result.data.adCampaignVO;
        $scope.title = result.data.title;
        if($scope.adCampaignVO.intervalHour){
            if (typeof($scope.adCampaignVO.intervalHour) !== "undefined") {
                $scope.adCampaignVO.intervalHour.split(",").forEach(function (hour) {
                    $scope.initData.intervalHour.forEach(function (item) {
                        if(item.key==hour){
                            item.checked=true
                        }
                    })
                })
            }
        }


        //广告排期
        if ($scope.adCampaignVO.scheduleDaysView == undefined) {
            $scope.adCampaignVO.scheduleDaysView = [['','']];
        } else {
            var sourceArr = $scope.adCampaignVO.scheduleDaysView;
            var resultArr = [];
            for(var i = 0; i < sourceArr.length; i++) {
                var j = parseInt(i / 3);
                if(angular.isUndefined(resultArr[j])) {
                    resultArr[j] = [];
                }
                resultArr[j].push(sourceArr[i]);
            }
            for(var m = 0; m < resultArr.length; m++) {
                resultArr[m][0] = new Date(resultArr[m][0]);
                resultArr[m][1] = new Date(resultArr[m][1]);
            }
            $scope.adCampaignVO.scheduleDaysView = resultArr;
        }

        $scope.addScheduling = function() {
            var arr = $scope.adCampaignVO.scheduleDaysView;
            var index = arr.length - 1;
            if(arr[index][0] && arr[index][1]) {
                arr.push(['','']);
            } else {
                ImsErr.open({message:"排期为空，不能新建"})
            }
        };
        $scope.delScheduling = function(index){
            var arr = $scope.adCampaignVO.scheduleDaysView;
            arr.splice(index,1);
        };

    });

    $scope.openStart = function(item) {
        item.openedStart=true;

        var $index = $scope.adCampaignVO.scheduleDaysView.indexOf(item);
        item.startDateOpt={
            minDate: $index ? $scope.adCampaignVO.scheduleDaysView[$index - 1][1] : '',
            maxDate: item[1]
        }
    };

    $scope.openEnd = function(item) {
        item.openedEnd=true;

        var $index = $scope.adCampaignVO.scheduleDaysView.indexOf(item);
        item.endDateOpt={
            minDate: item[0],
            maxDate: $index == ($scope.adCampaignVO.scheduleDaysView.length - 1) ? '' : $scope.adCampaignVO.scheduleDaysView[$index + 1][0]
        }
    };

    //点击确定
    $scope.submit=function () {
        //付费类型 其他未选-->input内容删除
        if ($scope.adCampaignVO.payType != '30'){
            $scope.adCampaignVO.memo = ""
        }
        //每日时段 数组-->字符串
        var ids=[];
        $scope.initData.intervalHour.forEach(function (item) {
            if(item.checked){
                ids.push(item.key)
            }
        });
        var obj = {checked:ids.toString()};
        $scope.adCampaignVO.intervalHour = obj.checked;
        //广告排期 标准时间--> yyyy-MM-dd
        var format = function(time, format){
            var t = new Date(time);
            var tf = function(i){return (i < 10 ? '0' : '') + i};
            return format.replace(/yyyy|MM|dd/g, function(a){
                switch(a){
                    case 'yyyy':
                        return tf(t.getFullYear());
                        break;
                    case 'MM':
                        return tf(t.getMonth() + 1);
                        break;
                    case 'dd':
                        return tf(t.getDate());
                        break;
                }
            });
        };
        var sourceTime = $scope.adCampaignVO.scheduleDaysView;
        var resultTime = [];
        for (var time = 0; time < sourceTime.length; time++) {
            var startTime = format(sourceTime[time][0], 'yyyy-MM-dd');
            var endTime = format(sourceTime[time][1], 'yyyy-MM-dd');
            resultTime.push(startTime + "~" + endTime);
        }
        $scope.adCampaignVO.scheduleDays = resultTime.toString();

        //跳转
        var scheduleDaysView = $scope.adCampaignVO.scheduleDaysView;
        var dateIsRight=true;

        angular.forEach(scheduleDaysView, function(data){
            (!data[0] || !data[1])?dateIsRight=false:"";
        });

        if(dateIsRight){
            if($scope.adCampaignVO.campaignName){
                if ($scope.adCampaignVO.adStyle && $scope.adCampaignVO.costType && $scope.adCampaignVO.costStrategy) {
                    if ($scope.adCampaignVO.status == 9) {
                        delete $scope.adCampaignVO.scheduleDaysView;
                        CampaignsManager.campaignsEdit(campaignsId,$scope.adCampaignVO).then(function(result){
                            if(result.data.c=='s'){
                                $state.go('campaigns.detail',{campaignsId:campaignsId},{reload:true})
                            }
                        });
                    } else {
                        delete $scope.adCampaignVO.scheduleDaysView;
                        CampaignsManager.campaignsEditAgain(campaignsId,$scope.adCampaignVO).then(function(result){
                            if(result.data.c=='s'){
                                $state.go('campaigns.detail',{campaignsId:campaignsId},{reload:true})
                            }
                        });
                    }
                }
            }
        }

    };

    //点击取消
    $scope.cancle = function() {
        $state.go('campaigns.detail',{campaignsId:campaignsId},{reload:true})
    };

    //model参数配置
    $scope.modelshortNameParam = {
        title: "广告合约选择",
        choose: function (selectedItem) {
            $scope.title.advShortName = selectedItem.name;
            $scope.formData.advertiserId = selectedItem.id;
        }
    };

    //model 点击打开。param：title文字、body数据、选择触发回调方法，size：model大小（big、small，默认中等大小）
    $scope.modelOpen = function (param, elm, size) {
        var modal = $uibModal.open({
            templateUrl: 'myModalContent.html',
            controller: 'advertiserModalController',
            size: 'normal',
            resolve: {
                param: param
            }
        });
        modal.result.then(function (result) {
            $scope.adCampaignVO.contractId = result.id
        });
    };

}]);
